package org.eae.eldf.webapp.controller.sys;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContext;

import org.eae.eldf.webapp.base.AbstractController;
import org.eae.eldf.webapp.common.bean.Result;
import org.eae.eldf.webapp.common.bean.ResultList;
import org.eae.eldf.webapp.common.constant.StateDefine;
import org.eae.eldf.webapp.vo.PageListVo;
import org.eae.eldf.webapp.vo.TreeVo;
import org.eae.eldf.dto.sys.OperatorRoleCheckDto;
import org.eae.eldf.dto.sys.SysOperatorQueryDto;
import org.eae.eldf.entity.sys.Authorization;
import org.eae.eldf.entity.sys.SysMenu;
import org.eae.eldf.entity.sys.SysOperator;
import org.eae.eldf.entity.sys.SysRole;
import org.eae.eldf.framework.json.JSONArray;
import org.eae.eldf.framework.pager.Pagination;
import org.eae.eldf.framework.persistence.Criteria;
import org.eae.eldf.framework.annotation.Token;
import org.eae.eldf.framework.spring.SpringSecurityUtils;
import org.eae.eldf.framework.utils.MD5;
import org.eae.eldf.service.sys.SysMenuService;
import org.eae.eldf.service.sys.SysOperatorService;
import org.eae.eldf.service.sys.SysRoleService;

@Controller
@RequestMapping("/sys")
public class SysOperatorController extends AbstractController<SysOperator> {

	private SysOperatorService operatorService;

	private SysRoleService roleService;
	
	private SysMenuService sysMenuService;
	
	private EhCacheCacheManager cacheManager;
	
	@Autowired
	public void setCacheManager(EhCacheCacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}

	@Autowired
	public void setSysMenuService(SysMenuService sysMenuService) {
		this.sysMenuService = sysMenuService;
	}

	@Autowired
	public void setOperatorService(SysOperatorService operatorService) {
		this.operatorService = operatorService;
	}

	@Autowired
	public void setRoleService(SysRoleService roleService) {
		this.roleService = roleService;
	}
	

	/**
	 * 查询列表页面
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/operator")
	public String initPage(@RequestParam(required = false) String searchValue,
			ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		return "/sys/operator/sys_operator";
	}
	
	/**
	 * 分页查询
	 * @param request
	 * @param response
	 * @param sysOperatorQueryDto
	 * @return
	 */
	@RequestMapping(value = "/operator/list")
	public @ResponseBody ResultList<SysOperator> pageList(
			HttpServletRequest request, 
			HttpServletResponse response,
			@ModelAttribute(value="sysOperatorQueryDto") SysOperatorQueryDto sysOperatorQueryDto){
		Pagination<SysOperator> pager = super.newPaginationInstance(sysOperatorQueryDto);
		pager = operatorService.queryPageUserList(pager, sysOperatorQueryDto);
		return outPageArrayList(pager,sysOperatorQueryDto);
	}

	/**
	 * 删除用户
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/operator/delete")
	public @ResponseBody
	Result delete(@ModelAttribute(value="sysOperator") SysOperator operator) {
		Result result = new Result(StateDefine.FLAG_SUCCESS, true);
		operatorService.delete(operator.getSysOperatorId());
		return result;
	}

	
	/**
	 * 新增用户
	 * 
	 * @param operator
	 * @return
	 */
	@RequestMapping(value = "/operator/add")
	@ResponseBody
	public Result insert(
			HttpServletRequest request,@ModelAttribute(value="sysOperator") SysOperator operator,
			@RequestParam(required = false)String roleIds) {
			RequestContext requestContext = new RequestContext(request);
			Result result = new Result(StateDefine.FLAG_SUCCESS, true);
			//判断用户名是否已经存在
			if(operatorService.queryCount(Criteria.create(SysOperator.class).where("susername", new Object[]{operator.getSusername()}))>0){
				result.setResultValue(false);
				result.setMessage(requestContext.getMessage("operator.msg.username.exist"));
			}else{
				operator.setSpassword(MD5.encode(operator.getSpassword()));
				operator.setBisdelete(0);
				operator.setBisadmin(0);
				operator.setDadddate(new Date());
				operator.setDcreatetime(new Date());
				operator.setDendlogintime(new Date());
				operator.setDlastlogintime(new Date());
				operator.setDlastupdatetime(new Date());
				operator.setSlastupdateuser(SpringSecurityUtils
						.getCurrentUserName());
				operatorService.insert(operator);
			}
		return result;
	}

	/**
	 * 编辑用户
	 * 
	 * @param id
	 * @param srealname
	 * @param smail
	 * @param smobile
	 * @param sphone
	 * @param bisfreeze
	 * @param searchValue
	 * @param sorting_column_order
	 * @param sorting_asc_desc
	 * @return
	 */
	@RequestMapping(value = "/operator/update", method = RequestMethod.POST)
	@ResponseBody
	public Result update(HttpServletRequest request,@ModelAttribute(value="sysOperator") SysOperator operator,
			@RequestParam(required = false)String roleIds) {
		Result result = new Result(StateDefine.FLAG_SUCCESS, true);
			operatorService.saveOperatorRole(Criteria.create(SysOperator.class)
					.set("srealname", operator.getSrealname()).set("smail", operator.getSmail())
					.set("smobile", operator.getSmobile()).set("sphone", operator.getSphone())
					.set("bisfreeze", operator.getBisfreeze()==null?0:operator.getBisfreeze())
					.where("sysOperatorId", new Object[] { operator.getSysOperatorId() }),operator.getSysOperatorId(),roleIds);
		return result;
	}

	/**
	 * 查询用户的角色
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/operator/role")
	@ResponseBody
	public List<OperatorRoleCheckDto> toRoleSettingPage(@ModelAttribute(value="sysOperator") SysOperator operator) {
		// 已有角色和未被分配的角色
		List<OperatorRoleCheckDto> roleList = operatorService
				.queryRoleByUser(operator.getSysOperatorId());
		return roleList;
	}

	

	/**
	 * 重置用户密码
	 * 
	 * @param id
	 * @param spassword
	 * @param spassword1
	 * @param username
	 * @param model
	 * @return
	 */
	@RequestMapping("/operator/changePwd")
	@ResponseBody
	public Result updateUserRole(@RequestParam(required = false) Long id,
			@RequestParam(required = false) String spassword,
			@RequestParam(required = false) String spassword1) {
		Result result = new Result(StateDefine.FLAG_SUCCESS, true);
		if (spassword.equals(spassword1)) {
			operatorService.update(Criteria.create(SysOperator.class)
					.set("spassword", MD5.encode(spassword))
					.where("sysOperatorId", new Object[] { id }));
		} else {
			result.setResultValue(false);
			result.setMessage("两次密码不一致");
		}
		return result;
	}
	
	@RequestMapping("/operator/menus")
	public @ResponseBody List<TreeVo> initMenuTree(HttpServletRequest request, HttpServletResponse response){
		Cache baseCache = cacheManager.getCache("baseCache");
		ValueWrapper value = baseCache.get("operator_all_menus");
		List<SysMenu> listMenu = null;
		if(null==value){
			listMenu = sysMenuService.queryList(Criteria.create(SysMenu.class));
			baseCache.put("operator_all_menus", listMenu);
		}else{
			listMenu = (List<SysMenu>)value.get();
		}
		
		HashSet<Long> perSet = operatorService.getOperatorMenus(SpringSecurityUtils.getCurrentUserName());
		Map<String, TreeVo> treeMap = new LinkedHashMap<String, TreeVo>();
		Locale locale = (Locale) request.getSession().getAttribute(
				SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
		//String lan = locale.getLanguage();
		
		TreeVo root = new TreeVo();
		for (SysMenu menu : listMenu) {
			if(menu.getBisleaf()==0 || perSet.contains(menu.getSysMenuId())){
				TreeVo tree = new TreeVo();
				tree.setId("menu_"+menu.getSysMenuId());
				tree.setText(menu.getSname());
				tree.setLeaf(menu.getBisleaf()==0?false:true);
				tree.setIcon(StringUtils.isBlank(menu.getSiconcls())?"":menu.getSiconcls());
				tree.setParentId(menu.getParentid()!=null?"menu_"+menu.getParentid():null);
				if (menu.getBisleaf() == 1) {
					tree.setUrl(menu.getSmenupath());
				}
				treeMap.put("menu_"+menu.getSysMenuId(), tree);
			}
		}
		Iterator<Map.Entry<String, TreeVo>> it = treeMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, TreeVo> entry = it.next();
			TreeVo tree = entry.getValue();
			if (StringUtils.isBlank(tree.getParentId())) {
				root.getMenus().add(tree);
			}else{
				TreeVo parent = treeMap.get(tree.getParentId());// 根据父Id查询
				if (parent != null) {
					parent.getMenus().add(tree);
				}
			}
		}
		root.removeNoRight();
		return root.getMenus();
	}

}
